<template>
  <div class="chat-container">
    <h2 style="text-align: center;color:deepskyblue;">AI数字人</h2>
    <el-card class="chat" style="margin-top:10px;height: 80vh;border-radius: 15px;border-color: #ccc;">
      <el-card class="main_chat">
        <div v-for="item in messages" :key="message.id" class="message">
          <div v-if="item.inputMessage != null && item.inputMessage !== ''" class="user-message">
            {{ item.inputMessage }}
          </div>
          <div v-if="item.aiResult != null && item.aiResult !== ''" class="bot-message" v-html="item.aiResult">

          </div>
        </div>

      </el-card>
      <el-input placeholder="提问" v-model.trim="inputMessage" :disabled="loading" @keyup.enter.native="sendMessage">
        <el-button slot="append" :icon="showIcon ? 'el-icon-s-promotion' : 'el-icon-video-pause'"
          :title="showIcon ? '向ai提问' : '停止回答'" @click="handleClick"></el-button>
      </el-input>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMessage: "",
      message: {
        inputMessage: "",
        aiResult: "",
        userId: null,
      },
      loading: false,
      eventSource: null,
      currentStreamMessageIndex: null,// 用于跟踪当前正在接收流式数据的消息索引
      showIcon: true,
    };
  },
  methods: {

    handleClick() {
      if (!this.showIcon) {
        this.showIcon = true;
        // 如果正在加载，则调用取消方法
        this.Destroy();
      } else {
        this.sendMessage();
      }
    },

    async sendMessage() {
      // 将用户输入的消息添加到消息列表中
      if (this.inputMessage.trim() === "") {
        return this.$message.info({
          message: "文本不能为空",
          duration: 1500
        })
      }

      if (this.inputMessage.trim() !== "") {
        var userId = window.sessionStorage.getItem("userId");
        this.messages.push({
          id: Date.now(),
          inputMessage: this.inputMessage,
          userId: parseInt(userId)
        });

        // 开始接收流式数据前的初始化
        this.currentStreamMessageIndex = this.messages.length; // 设置当前消息的索引

        // 这里可以是调用 GPT API 的逻辑
        this.message.inputMessage = this.inputMessage.trim();
        this.message.userId = userId;
        // 清空输入框
        this.inputMessage = "";
        this.loading = true;
        this.showIcon = false;

        const url = new URL('/api/ai/stream', 'http://localhost:8889');
        url.searchParams.append('msg', this.message.inputMessage);
        // console.log(window.sessionStorage.getItem("token"));
        this.eventSource = new EventSource(url.href);

        this.eventSource.addEventListener('message', (event) => {
          console.log(event.data)
          // 检查是否有正在进行的流式消息
          if (this.currentStreamMessageIndex !== null && this.currentStreamMessageIndex < this.messages.length) {
            // 如果有，追加数据到现有的 aiResult 字段
            this.messages[this.currentStreamMessageIndex].aiResult += event.data;
          } else {
            // 否则，创建一个新的消息对象
            this.messages.push({
              id: Date.now(),
              aiResult: event.data,
              userId: userId
            });
            this.currentStreamMessageIndex = this.messages.length - 1; // 更新当前消息的索引
          }
        });

        this.eventSource.addEventListener('error', (event) => {
          console.error('Error in SSE:', event);
          this.eventSource.close();
          this.loading = false;
        });
      }
    },
    Destroy() {
      this.eventSource.close();
      this.$message.info({
        message: "已停止回答",
        duration: 2000
      })
      this.loading = false;

    },
  },

  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
};
</script>
<style scoped lang='less'>
//.chat-container {
//  display: flex;
//  flex-direction: column;
//  height: 100vh;
//}
.main_chat {
  margin-bottom: 10px;
  height: 70vh;
  background-size: cover;
  background: url(https://xxx.xiaobaitiao.icu/img/icu/202312211243632.jpg) no-repeat 0px 0px;
  border-radius: 10px;
  overflow-y: scroll;
}

.message {
  display: flex;
  flex-direction: column;
}

.user-message {
  display: flex;
  flex-direction: row;
  background-color: #e7f7ff;
  padding: 10px;
  border-radius: 10px;
  align-self: flex-end;
  text-align: right;
  margin-top: 10px;

}

.bot-message {
  background-color: #f4f6f8;
  padding: 10px;
  border-radius: 10px;
  text-align: left;
  align-self: flex-start;
  margin-top: 10px;
  white-space: pre-wrap;
}
</style>